package com.bishe.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bishe.pojo.Comment;
import com.bishe.mapper.CommentDao;
import com.bishe.pojo.Student;
import com.bishe.pojo.Teacher;
import com.bishe.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.service.StudentService;
import com.bishe.service.TeacherService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lwx
 * @since 2022-04-14
 */
@Service
public class CommentServiceImp extends ServiceImpl<CommentDao, Comment> implements CommentService {

    @Resource
    private StudentService studentService;

    @Resource
    private TeacherService teacherService;

    @Override
    public List<Comment> getComments() {

        List<Student> students = studentService.list();
        Map<String, String> studentMap = students.stream()
                .collect(Collectors.toMap(Student::getId, Student::getUserName));

        List<Teacher> teachers = teacherService.list();
        Map<String, String> teacherMap = teachers.stream()
                .collect(Collectors.toMap(Teacher::getId, Teacher::getName));

        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.putAll(studentMap);
        resultMap.putAll(teacherMap);

        List<Comment> list = this.list(new LambdaQueryWrapper<Comment>()
                .orderByDesc(Comment::getCreateTime));

        for (Comment comment : list) {
            if (CollUtil.isNotEmpty(resultMap)){
                comment.setCreateByName(resultMap.get(comment.getCreateBy()));
            }
        }
        return list;
    }

    @Override
    public void addComment(Comment comment) {
        comment.setId(StrUtil.uuid());
        comment.setCreateBy(StpUtil.getLoginId().toString());
        comment.setCreateTime(new Date());
        save(comment);
    }


}
